﻿using System;
using System.Transactions;
using Microsoft.EntityFrameworkCore;
using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore.Uow;
using Abp.MultiTenancy;
using FwProject.EntityFrameworkCore.Seed.Host;
using FwProject.EntityFrameworkCore.Seed.Tenants;
using System.Collections.Generic;
using FwProject.EntityFrameworkCore.GloabDiagnosticInitializer;
using Microsoft.Extensions.Configuration;

namespace FwProject.EntityFrameworkCore.Seed
{
    public static class SeedHelper
    {
        public static void SeedHostDb(IIocResolver iocResolver)
        {
            WithDbContext<FwProjectDbContext>(iocResolver, SeedHostDb);
        }

        public static void SeedHostDb(FwProjectDbContext context)
        {
            context.SuppressAutoSetTenantId = true;

            // Host seed
            new InitialHostDbBuilder(context).Create();

            // Default tenant seed (in host database).
            new DefaultTenantBuilder(context).Create();
            new TenantRoleAndUserBuilder(context, 1).Create();
        }

        private static void WithDbContext<TDbContext>(IIocResolver iocResolver, Action<TDbContext> contextAction)
            where TDbContext : DbContext
        {
            using (var uowManager = iocResolver.ResolveAsDisposable<IUnitOfWorkManager>())
            {
                using (var uow = uowManager.Object.Begin(TransactionScopeOption.Suppress))
                {
                    var context = uowManager.Object.Current.GetDbContext<TDbContext>(MultiTenancySides.Host);

                    contextAction(context);

                    uow.Complete();

#if DEBUG
                    var config = new ConfigurationBuilder().AddJsonFile("hosting.json", optional: true).Build();
                    List<ConnnectionSwtich> connnectionSwtichoptions = new List<ConnnectionSwtich>();
                    config.GetSection("Db").Bind(connnectionSwtichoptions);
                    List<IProfilerDiagnosticListener> profilerDiagnosticListeners = new List<IProfilerDiagnosticListener>();
                    profilerDiagnosticListeners.Add(new RelationalDiagnosticListener<TDbContext>(connnectionSwtichoptions,uowManager.Object.Current));
                    DiagnosticInitializer diagnosticInitializer = new DiagnosticInitializer(profilerDiagnosticListeners);
                    diagnosticInitializer.Start();
#endif
                }
            }
        }
    }
}
